package com.hehe.boot.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.hehe.boot.pojo.Result;
import com.hehe.boot.pojo.User;
import com.hehe.boot.pojo.UserHttp.UserRegisterRequest;
import com.hehe.boot.pojo.UserHttp.UserRegisterResponse;
import com.hehe.boot.pojo.UserHttp.UserSetTelephoneRequest;
import com.hehe.boot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@CrossOrigin(origins = "*")
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/register")
    public Result<UserRegisterResponse> Register(@RequestBody UserRegisterRequest userRegisterRequest){

        Long userId = userService.register(userRegisterRequest.getUsername(),
                userRegisterRequest.getPassword());

        UserRegisterResponse response = new UserRegisterResponse();
        response.setUserId(userId);

        return Result.success(response);
    }

    @PostMapping("/setTelephone")
    public Result SetTelephone(@RequestBody UserSetTelephoneRequest request){
        Boolean flag = userService.setTelephone(request.getUserId(),request.getTelephone());

        if (flag != true){
            return Result.error("user setTelephone error: Update telephone fails");
        }

        return Result.success();
    }

    @GetMapping("/find")
    public Result<IPage<User>> findall(@RequestParam(required = false) String query,
                                          @RequestParam Integer page){
        if (query != null && !query.isEmpty()) {
            return Result.success(userService.getProPageLike(query,page));
        }
        return Result.success(userService.getProPage(page));
    }

    @GetMapping("/findById")
    public Result<User> findById(@RequestParam String id){
        return Result.success(userService.getById(id));
    }

    @PostMapping("/insert")
    public Result<Boolean> insert(@RequestBody User user){
        System.out.println("sdad   "+ user);
        return Result.success(userService.insertUser(user));
    }

    @PostMapping("/update")
    public Result update(@RequestBody User user){
        return Result.success(userService.updateUser(user));
    }

    @PostMapping("/delete")
    public Result delete(@RequestBody User user){
        return Result.success(userService.deleteUser(user));
    }
}